
import { Injectable } from "@angular/core";
import { Router } from '@angular/router';
import { Observable, EMPTY, throwError, of } from 'rxjs';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse
} from '@angular/common/http';
import { tap } from 'rxjs/operators';
import { catchError } from 'rxjs/operators';
const ignoreToken = ['FHOneMapser'];
@Injectable({
  providedIn: 'root'
})
export class DefaultInterceptor implements HttpInterceptor {
  constructor(private router: Router) { }
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const url = req.url;
    const needToken = ignoreToken.filter(u => url.match(u));
    // console.log('needToken', needToken);
    const authToken = 'Bearer ' + JSON.parse(sessionStorage.getItem('token'));
    console.log("DefaultInterceptor", authToken)
    if (authToken && needToken.length > 0) {
      // 服务请求时所有的请求加入token
      const authReq = req.clone({
        headers: req.headers.set('Authorization', authToken),
        url: req.url
      });
      // 服务器响应结果
      return next.handle(authReq).pipe(tap(event => {
        if (event instanceof HttpResponse) {
          this.handleData(event);
        }
      }, error => {
        this.handleData(error);
       /// this.router.navigate(['login']);
        // token过期 服务器错误等处理
      }));

     }
    // 若token不存在，则不对请求进行处理
    return next.handle(req).pipe(tap(event => {
      if (event instanceof HttpResponse) {
        // console.log(event);
        this.handleData(event);
      }
    }, error => {
      this.handleData(error);
    }),
      // 另一种方法也可行
      // catchError((error: HttpErrorResponse) => {
      //   if (error.status === 401) {
      //     this.router.navigate(['login']);
      //   }
      //   return EMPTY;
      // })
    );
  }
  handleData(event: HttpResponse<any> | HttpErrorResponse): Observable<any> {
   // console.log(event.status);
  //  const status = event.headers;
    // 业务处理：一些通用操作
    switch (event.status) {
      case 200:
        if (event instanceof HttpResponse) {
          const body: any = event.body;
          //  console.log(event);
        }
        break;
      case 401: // 未登录状态码
        // this.goTo('/login');
        console.log('未登录状态码');
        this.router.navigate(['login']);
        break;
      case 404:
      case 500:
        console.log('后台接口发生错误');
        // console.log(event);
        break;
      default:
        return of(event);
    }
  }
}
